<template>
  <div class="transfer-container" ref="shuttleBoxRef">
    <div class="list-container">
      <div class="search-header">
        <div class="list-title">待选参数列表</div>
        <input
          v-model="searchQuery"
          type="text"
          placeholder="搜索参数..."
          class="tech-input"
        />
      </div>
      <div class="parameter-list">
        <div v-for="item in filteredParams" :key="item.label" class="parameter-item-container">
          <div class="parameter-item" :class="{'has-children': item.children && item.children.length > 0}">
            <div class="parameter-item-content">
              <label class="tech-checkbox">
                <input
                  type="checkbox"
                  :value="item.label"
                  :checked="selectedItems.available.includes(item.label)"
                  @change="selectItem(item, 'available', $event)"
                />
                <span class="checkbox-custom"></span>
                <span class="checkbox-label">{{ item.label }}</span>
              </label>
              <button v-if="item.children && item.children.length > 0"
                class="expand-btn"
                @click.stop="toggleExpand(item.label)">
                <svg class="h-3 w-3" :class="{'rotate-180': expandedItems.has(item.label)}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <path d="M19 9l-7 7-7-7" />
                </svg>
              </button>
            </div>
          </div>

          <div v-if="item.children && item.children.length > 0 && expandedItems.has(item.label)"
            class="parameter-children">
            <div v-for="child in item.children" :key="child.label" class="parameter-child-item">
              <label class="tech-checkbox">
                <input
                  type="checkbox"
                  :value="child.label"
                  :checked="selectedItems.available.includes(child.label)"
                  @change="selectItem(child, 'available', $event)"
                />
                <span class="checkbox-custom"></span>
                <span class="checkbox-label">{{ child.label }}</span>
              </label>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="list-container">
      <div class="search-header">
        <div class="list-title">已选参数列表</div>
        <input
          v-model="selectedSearchQuery"
          type="text"
          placeholder="搜索参数..."
          class="tech-input"
        />
      </div>
      <div class="parameter-list">
        <div v-for="item in filteredSelectedParams" :key="item.label" class="parameter-item-container">
          <div class="parameter-item">
            <div class="parameter-item-content">
              <span class="checkbox-label">{{ item.label }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {ref, computed, onMounted, watch} from 'vue'
import WithAPI from '@/views/parameter/parameter.api.ts'
import API from "@/views/playbackTask/playbackTask.api.ts";

interface Parameter {
  id: string;
  name: string;
  type?: string;
  children?: Parameter[];
}

interface SelectedItem {
  value: string;
  label: string;
  type: string;
  children?: SelectedItem[];
}

const props = defineProps<{
  taskName: {
    type: any
  },
  availableName: {
    type: string
  },
  parameters: Array<Parameter>
  darkMode: Boolean
}>()

// 展开的参数ID数组
const expandedItems = ref<Set<string>>(new Set())
// 已选参数列表的展开状态
const selectedExpandedItems = ref<Set<string>>(new Set())

const emit = defineEmits<{
  (e: 'update:selectedParams', value: Array<SelectedItem>): void
}>()

const searchQuery = ref('')
const selectedSearchQuery = ref('')

async function getTaskList() {
  try {
    const res:any = await API.queryAllTask();
    if (res && res.code === 200) {
      for (const item of res.data) {
        if (props.taskName === item.name) {
          const parsedParams = JSON.parse(item.parameters);
          selectedParams.value = parsedParams.map((param: any) => ({
            value: param.id,
            label: param.name || param.label,
            type: param.type
          }));
          break;
        }
      }
    }
  } catch (error) {
    console.error('Failed to fetch task list:', error);
  }

  if (props.parameters) {
    let itemList: SelectedItem[] = [];
    props.parameters.forEach((item: Parameter) => {
      const newItem: SelectedItem = {
        value: item.id,
        label: item.name,
        type: item.type || '',
        children: item.children?.map((child: Parameter) => ({
          value: child.id,
          label: child.name,
          type: child.type || '',
          children: child.children?.map((grandChild: Parameter) => ({
            value: grandChild.id,
            label: grandChild.name,
            type: grandChild.type || ''
          }))
        }))
      };
      itemList.push(newItem);

      // 检查并添加已选参数到selectedItems.available
      const isSelected = selectedParams.value.some(param =>
        param.label === newItem.label ||
        (param.children && param.children.some(c => c.label === newItem.label))
      );
      if (isSelected && !selectedItems.value.available.includes(newItem.label)) {
        selectedItems.value.available.push(newItem.label);
      }

      // 检查子节点是否已选
      if (newItem.children) {
        newItem.children.forEach((child: SelectedItem) => {
          const isChildSelected = selectedParams.value.some(param =>
            param.label === child.label ||
            (param.children && param.children.some(c => c.label === child.label))
          );
          if (isChildSelected && !selectedItems.value.available.includes(child.label)) {
            selectedItems.value.available.push(child.label);
          }
        });
      }
    });
    originalParams.value = [...itemList];
    availableParams.value = itemList;
  }
}
const filteredSelectedParams = computed(() => {
  // 创建一个映射来存储所有已选参数
  const selectedMap = new Map(selectedParams.value.map(param => [param.label, param]))
  
  // 扁平化处理函数
  const flattenItems = (items: SelectedItem[]): SelectedItem[] => {
    return items.reduce((acc: SelectedItem[], item) => {
      if (selectedMap.has(item.label)) {
        acc.push({
          value: item.value,
          label: item.label,
          type: item.type
        })
      }
      
      if (item.children && item.children.length > 0) {
        acc.push(...flattenItems(item.children))
      }
      
      return acc
    }, [])
  }

  // 获取扁平化的已选参数列表
  const flattenedItems = flattenItems(availableParams.value)
  
  // 应用搜索过滤
  return flattenedItems.filter(item => {
    if (!item || typeof item !== 'object') return false
    return item.label && typeof item.label === 'string'
      ? item.label.toLowerCase().includes(selectedSearchQuery.value.toLowerCase())
      : false
  })
})
const originalParams = ref<SelectedItem[]>([])
const availableParams = ref<SelectedItem[]>([])
const filteredParams = computed(() => {
  const filterItem = (item: SelectedItem) => {
    if (!item || typeof item !== 'object') return false

    const matchesSearch = item.label && typeof item.label === 'string'
      ? item.label.toLowerCase().includes(searchQuery.value.toLowerCase())
      : false

    if (item.children && Array.isArray(item.children) && item.children.length > 0) {
      const filteredChildren = item.children
        .filter((child: SelectedItem) => child && typeof child === 'object')
        .map((child: SelectedItem) => ({
          value: child.value,
          label: child.label,
          type: item.type,
          children: child.children
        }))
        .filter(child =>
          child && child.label && typeof child.label === 'string'
          ? child.label.toLowerCase().includes(searchQuery.value.toLowerCase())
          : false
        )

      if (filteredChildren.length > 0 || matchesSearch) {
        return {
          ...item,
          children: filteredChildren
        }
      }
    }

    return matchesSearch
  }

  return availableParams.value
    .map((item: SelectedItem) => ({
      value: item.value,
      label: item.label,
      type: item.type,
      children: item.children
    }))
    .filter(filterItem)
})

const selectedParams = ref<SelectedItem[]>([])
const selectedItems = ref<{
  available: string[];
  selected: string[];
}>({
  available: [],
  selected: []
})

// 切换参数展开/折叠状态
const toggleExpand = (itemValue: string, isSelectedList: boolean = false) => {
  const targetSet = isSelectedList ? selectedExpandedItems : expandedItems
  if (targetSet.value.has(itemValue)) {
    targetSet.value.delete(itemValue)
  } else {
    targetSet.value.add(itemValue)
  }
}

const selectItem = (item: SelectedItem, type: 'available' | 'selected', event: Event) => {
  const checkbox = event.target as HTMLInputElement
  const checked = checkbox.checked
  const itemValue = item.label

  if (checked) {
    // 选中项
    if (!selectedItems.value[type].includes(itemValue)) {
      selectedItems.value[type].push(itemValue)

      // 自动添加到已选列表，保持与待选列表相同的顺序
      if (type === 'available') {

        selectedParams.value.push(item)
        // 找到当前项在待选列表中的索引
        // const availableIndex = availableParams.value.findIndex(param => param.value === itemValue)
        // if (availableIndex !== -1) {
        //   // 在已选列表中找到第一个索引大于当前项在待选列表中索引的位置
        //   const insertIndex = selectedParams.value.findIndex(param => {
        //     const paramIndex = availableParams.value.findIndex(p => p.value === param.value)
        //     return paramIndex > availableIndex
        //   })
          
        //   // 处理子节点
        //   let itemToAdd = { ...item }
        //   if (item.children && item.children.length > 0) {
        //     // 对子节点进行排序
        //     itemToAdd.children = item.children
        //       .map(child => {
        //         const childIndex = availableParams.value[availableIndex].children?.findIndex(
        //           c => c.value === child.value
        //         )
        //         return { ...child, originalIndex: childIndex }
        //       })
        //       .sort((a, b) => {
        //         if (a.originalIndex === undefined) return 1
        //         if (b.originalIndex === undefined) return -1
        //         return a.originalIndex - b.originalIndex
        //       })
        //       .map(({ originalIndex, ...child }) => child)
        //   }
          
        //   if (insertIndex === -1) {
        //     // 如果没有找到更大的索引，则添加到末尾
        //     selectedParams.value.push(itemToAdd)
        //   } else {
        //     // 在找到的位置插入
        //     selectedParams.value.splice(insertIndex, 0, itemToAdd)
        //   }
        // } else {
        //   // 如果在待选列表中找不到，则添加到末尾
        //   selectedParams.value.push(item)
        // }
        emit('update:selectedParams', selectedParams.value)
      }
    }
  } else {
    // 取消选中
    selectedItems.value[type] = selectedItems.value[type].filter((name: string) => name !== itemValue)

    // 自动从已选列表移除
    if (type === 'available') {
      selectedParams.value = selectedParams.value.filter(param => param.label !== itemValue)
      emit('update:selectedParams', selectedParams.value)
    }
  }
}

// 添加 watch 来监听搜索查询的变化
watch([searchQuery, selectedSearchQuery], () => {
  // 当搜索查询变化时，确保已选参数保持不变
  emit('update:selectedParams', selectedParams.value)
})
const shuttleBoxRef = ref<HTMLElement | null>(true)
onMounted(() => {
  getTaskList();
})
</script>

<style scoped>
.transfer-container {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 20px;
  height: 100%;
  padding: 20px;
    background: var(--se-main-bg-color);
}

.transfer-container::before{
  background: var(--se-main-bg-color);
}

.list-container {
  flex: 1;
  border-radius: 8px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  position: relative;
  height: 500px;
    background: var(--se-sub-plate-bg-color);
    border-color: transparent;
}

.list-container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 3px;
  background: none
}

.search-header {
  padding: 12px 16px;
    border-bottom: transparent;
    background: var(--se-sub-plate-bg-color);
}

.list-title {
  font-size: 16px;
  font-weight: 600;
    color: var(--text-color);
  margin-bottom: 8px;
}

.tech-input {
  width: 100%;
  padding: 8px 12px;
  font-size: 15px;
  border-radius: 4px;
  /*transition: all 0.2s ease;*/
  background: var(--input-background);
  border: 1px solid var(--input-border-color);
  color: var(--text-color);
  box-shadow: inset 0 0 5px var(--input-shadow-color);
}
.tech-input::placeholder {
  color: var(--preview-text-color);
}
.tech-input:focus {
  outline: none;
  border-color: rgba(30, 64, 175, 0.4);
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
}

.parameter-list {
  flex: 1;
  overflow-y: auto;
  padding: 12px 16px;
    background: var(--se-sub-plate-bg-color);
}

.parameter-item-container {
  display: flex;
  flex-direction: column;
  margin-bottom: 2px;
}

.parameter-item {
  padding: 4px 0;
  transition: background-color 0.2s;
  border-radius: 4px;
}

.parameter-item:hover {
  background-color: rgba(30, 64, 175, 0.05);
}

.parameter-item.has-children {
  cursor: pointer;
}

.parameter-item-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.tech-checkbox {
  display: flex;
  align-items: center;
  gap: 10px;
  cursor: pointer;
  position: relative;
  flex: 1;
}

.tech-checkbox input {
  position: absolute;
  opacity: 0;
  cursor: pointer;
  height: 0;
  width: 0;
}

.checkbox-custom {
    position: relative;
    height: 18px;
    width: 18px;
    min-width: 18px;
    border-radius: 4px;
    border: 1px solid var(--btn-click-color);
    background-color: var(--ant-checkbox-inner);
    color: var(--global-color-white);
}

.tech-checkbox input:checked ~ .checkbox-custom {
    color: var(--global-color-white);
    background-color: var(--ant-checkbox-checked);
    border-color: var(--btn-click-color);
}

.checkbox-custom:after {
    content: "";
    position: absolute;
    display: none;
    left: 6px;
    top: 2px;
    width: 5px;
    height: 10px;
    border-width: 0 2px 2px 0;
    transform: rotate(45deg);
}

.tech-checkbox input:checked ~ .checkbox-custom:after {
    display: block;
}

.checkbox-label {
  color: var(--text-color);
  font-size: 14px;
}

.parameter-children {
  margin-left: 20px;
  border-left: 1px dashed rgba(30, 64, 175, 0.2);
  padding-left: 10px;
  animation: slideDown 0.2s ease-out;
}

.parameter-child-item {
  padding: 4px 0;
  margin-left: 5px;
  transition: background-color 0.2s;
  border-radius: 4px;
}

.parameter-child-item:hover {
  background-color: rgba(30, 64, 175, 0.05);
}

.expand-btn {
  background: none;
  border: none;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: #64748b;
  padding: 0;
  margin-right: 4px;
  transition: transform 0.2s;
}

.expand-btn svg {
  transition: transform 0.2s;
}

.expand-btn svg.rotate-180 {
  transform: rotate(180deg);
}

.button-container {
  display: flex;
  flex-direction: column;
  gap: 10px;
  justify-content: center;
  padding: 0 10px;
  position: relative;
  transform: translateY(200%);
}

.button-container button {
  padding: 8px 16px;
  background: rgb(237, 243, 255);
  border: 1px solid rgb(196, 216, 255);
  color: #1e3a8a;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.button-container button:hover {
  background: rgb(224, 235, 255);
  border-color: rgb(165, 195, 255);
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@media (max-width: 1024px) {
  .transfer-container {
    gap: 10px;
    padding: 10px;
  }
  .list-container {
    height: 400px;
  }
  .list-title {
    font-size: 14px;
  }
  .tech-input {
    font-size: 12px;
    padding: 6px 10px;
  }
  .checkbox-label {
    font-size: 12px;
  }
  .checkbox-custom {
    height: 16px;
    width: 16px;
    min-width: 16px;
  }
  .checkbox-custom:after {
    left: 5px;
    top: 1px;
    width: 4px;
    height: 8px;
  }
  .parameter-children {
    margin-left: 15px;
  }
  .expand-btn {
    width: 18px;
    height: 18px;
  }
  .button-container button {
    font-size: 12px;
    padding: 6px 12px;
  }
}

</style>
